import userApi from "../services/user"
export default {
    namespaced: true,
    state: {
        data: [],
        UserUpde: {},
        total: 0,
        isLoading: false,
        condition: {
            page: 1,
            limit: 3,
            key: "",
            field: "",
            sort: ""
        },
        login: {
            isLogin: false,
            role:"",
            loginName: ""
        }
    },
    mutations: {
        setLogin(state,login){
            state.login=login
        },
        setIsLoading(state, isLoading) {
            state.isLoading = isLoading
        },
        setCondition(state, condition) {
            state.condition = {
                ...state.condition,
                ...condition
            }
        },
        setTotal(state, total) {
            state.total = total
        },
        saveData(state, users) {
            state.data = users
        },
        deleteUser(state, id) {
            state.data = state.data.filter(it => it._id !== id)
        },
        getByIdUser(state, u) {
            state.UserUpde = u
        }
    },
    actions: {
        async saveData(context) {
            context.commit("setIsLoading", true)
            const res = await userApi.getUserAll(context.state.condition)
            context.commit("saveData", res.data)
            context.commit("setTotal", res.count)
            context.commit("setIsLoading", false)
        },
        async deleteUser(context, id) {
            await userApi.deleteUser(id)
            context.commit("deleteUser", id)
        },
        async getByIdUser(context, id) {
            const u = await userApi.getUserById(id)
            context.commit("getByIdUser", u.data)
        },
        async updeUser(context, user) {
            await userApi.modifyUser(user)
        },
        async addUser(context, user) {
            await userApi.addUser(user)
        }
    }
}